<template>
  <div class="picture-detail">
    <div class="main-content" v-if="picture">
      <!-- 左侧：图片展示 -->
      <el-image :src="picture.url" fit="cover" class="main-image" />

      <!-- 右侧：图片详情 -->
      <el-card class="detail-card">
        <h2>{{ picture.name }}</h2>
        <p class="introduction">{{ picture.introduction }}</p>

        <div class="metadata">
          <div class="meta-item">
            <span>分辨率</span>
            <span>{{ picture.picWidth }}x{{ picture.picHeight }}</span>
          </div>
          <div class="meta-item">
            <span>格式</span>
            <span>{{ picture.picFormat }}</span>
          </div>
          <div class="meta-item">
            <span>大小</span>
            <span>{{ (picture.picSize / 1024 / 1024).toFixed(2) }} MB</span>
          </div>
          <div class="meta-item">
            <span>上传者</span>
            <span>{{ picture.user ? picture.user.userName : '匿名者' }}</span>
          </div>
        </div>

        <div class="tags">
          <el-tag v-for="tag in picture.tags" :key="tag" type="info">{{ tag }}</el-tag>
        </div>

        <div class="metrics">
          <div class="metric-item">
            <el-icon><Download /></el-icon>
            <span>{{ picture.downloadCount || '0' }}</span>
          </div>
          <div class="metric-item">
            <Icons :name="picture.isLiked ? 'icon-aixin' : 'icon-xihuan1'">
              {{ picture.likeCount || '0' }}
            </Icons>
          </div>
          <div class="metric-item">
            <el-icon><ChatDotSquare /></el-icon>
            <span>{{ picture.commentCount || '0' }}</span>
          </div>
        </div>

        <div class="create-time">
          <span>创建时间</span>
          <span>{{ dayjs(picture.createTime).format('DD/MM/YYYY') }}</span>
        </div>

        <div class="actions">
          <el-button type="primary" @click="handleDownload">
            <el-icon><Download /></el-icon>
            下载图片</el-button
          >
          <el-button @click="handleLike">
            <Icons :name="picture.isLiked ? 'icon-aixin' : 'icon-xihuan1'">
              {{ picture.isLiked ? '取消点赞' : '点赞' }}
            </Icons>
          </el-button>
          <el-button @click="showComments">
            <el-icon><ChatDotSquare /></el-icon> 查看评论
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 评论抽屉 -->
    <el-drawer
      v-model="commentDrawerVisible"
      title="图片评论"
      direction="rtl"
      :size="drawerSize"
      @close="handleClose"
    >
      <div class="comment-container">
        <!-- 评论列表 -->
        <div class="comment-list">
          <div v-if="loading" class="loading-container">
            <el-skeleton animated />
          </div>
          <div v-else class="comments-wrapper">
            <div v-for="comment in commentList" :key="comment.id" class="comment-item">
              <CommentItem
                :comment="comment"
                :isRoot="true"
                @delete="handleDeleteComment(comment.id)"
                @reply="handleReplyComment"
              />
            </div>
          </div>
          <div v-if="commentList.length === 0 && !loading" class="empty-comment">
            <div class="empty-icon">
              <i class="el-icon-chat-line-round"></i>
            </div>
            <p>暂无评论，快来发表你的看法吧</p>
          </div>
        </div>

        <!-- 发布评论区域 -->
        <div class="publish-comment">
          <el-form :model="newComment" ref="commentForm" label-width="0px">
            <el-form-item>
              <el-input
                v-model="newComment.content"
                type="textarea"
                :rows="3"
                placeholder="请输入评论内容..."
                @keyup.enter="publishComment"
              />
            </el-form-item>
            <el-form-item>
              <el-button :loading="publishing" type="primary" @click="publishComment">
                发布评论
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { getPictureByIdAPI, downloadPictureAPI } from '@/api/pictureAPI'
import { likeAPI, unlikeAPI } from '@/api/likesAPI'
import { useRoute } from 'vue-router'
import dayjs from 'dayjs'
import { getCommentsByPictureIdAPI, addCommentAPI, deleteCommentAPI } from '@/api/commentsAPI'
import { ElMessage, ElMessageBox } from 'element-plus'

import CommentItem from '@/components/CommentItem.vue'

const route = useRoute()

// 图片数据
const picture = ref()

// 获取图片详情
const getPictureById = async () => {
  console.log('获取图片详情，ID:', route.params.id)

  const res = await getPictureByIdAPI(route.params.id)

  picture.value = res.data
  console.log('获取图片详情:', picture.value)
}

//下载图片
const handleDownload = () => {
  downloadPictureAPI(picture.value.id).then(() => {
    window.open(picture.value.url)
    ElMessage.success('下载成功')
    getPictureById()
  })
}

const handleLike = async () => {
  console.log('点赞图片')
  if (picture.value.isLiked) {
    await unlikeAPI(picture.value.id)
  } else {
    await likeAPI(picture.value.id)
  }
  await getPictureById()
}

const commentDrawerVisible = ref(false)
const showComments = () => {
  console.log('查看评论')
  commentDrawerVisible.value = true
}

// 状态管理
const drawerSize = ref('40%') // 抽屉大小
const commentList = ref([]) // 评论列表
const loading = ref(false) // 是否加载中
const publishing = ref(false) // 是否正在发布评论
const newComment = reactive({
  content: '',
  parentId: null,
}) // 新评论数据
const currentReplyTo = ref(null) // 当前回复的评论
const commentForm = ref(null) // 评论表单引用

// 获取评论列表
const getComments = async () => {
  loading.value = true
  try {
    const res = await getCommentsByPictureIdAPI(route.params.id)
    commentList.value = res.data || []
    console.log('获取评论列表:', commentList.value)
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试')
    console.error('获取评论列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 发布评论
const publishComment = async () => {
  if (!newComment.content.trim()) {
    ElMessage.warning('评论内容不能为空')
    return
  }
  publishing.value = true
  try {
    const commentData = {
      pictureId: route.params.id,
      content: newComment.content.trim(),
      parentId: newComment.parentId,
    }
    await addCommentAPI(commentData)
    ElMessage.success('评论发布成功')
    resetCommentForm()
    getComments() // 刷新评论列表
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试')
    console.error('发布评论失败:', error)
  } finally {
    publishing.value = false
  }
}

// 处理删除评论
const handleDeleteComment = async (commentId) => {
  ElMessageBox.confirm('确定要删除这条评论吗？删除后将无法恢复', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      await deleteCommentAPI(commentId)
      getComments() // 刷新评论列表
      ElMessage.info('评论删除成功')
    })
    .catch(() => {
      // 取消操作，无需处理
      console.log('取消删除评论')
    })
}

// 处理回复评论
const handleReplyComment = (comment) => {
  console.log('回复评论:', comment)

  if (currentReplyTo.value?.id === comment.id) {
    // 关闭回复
    resetCommentForm()
  } else {
    // 打开回复
    currentReplyTo.value = comment
    newComment.parentId = comment.id
    newComment.content = `@${comment.user.userName} `

    // 滚动到评论框
    setTimeout(() => {
      const commentBox = document.querySelector('.publish-comment')
      if (commentBox) {
        commentBox.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
        const textarea = commentBox.querySelector('textarea')
        if (textarea) {
          textarea.focus()
          textarea.setSelectionRange(newComment.content.length, newComment.content.length)
        }
      }
    }, 300)
  }
}

// 重置评论表单
const resetCommentForm = () => {
  newComment.content = ''
  newComment.parentId = null
  currentReplyTo.value = null
  if (commentForm.value) {
    commentForm.value.resetFields()
  }
}

// 关闭抽屉
const handleClose = () => {
  commentDrawerVisible.value = false
  resetCommentForm()
}

onMounted(async () => {
  await getPictureById()
  await getComments()
  console.log('组件挂载完成，图片ID:', route.params.id)
})
</script>

<style scoped>
.picture-detail {
  display: flex;
  justify-content: center;
  padding: 20px;
  background-color: #f5f5f5;
}

.main-content {
  display: flex;
  width: 100%;
  max-width: 1200px;
}

.main-image {
  width: 70%;
  border-radius: 8px;
  margin-right: 20px;
  border: 1px solid #e5e5e5;
}

.detail-card {
  width: 30%;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

h2 {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
}

.introduction {
  font-size: 14px;
  color: #666;
  margin-bottom: 15px;
}

.metadata {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 15px;
}

.meta-item {
  width: 50%;
  margin-bottom: 10px;
}

.meta-item span:first-child {
  color: #666;
  margin-right: 10px;
}

.color-swatch {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.color-circle {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  margin-left: 10px;
}

.tags {
  margin-bottom: 15px;
}

.el-tag {
  margin-right: 8px;
  margin-bottom: 8px;
  background-color: #e6f7fa;
  color: #000;
}

.metrics {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.metric-item {
  display: flex;
  align-items: center;
}

.metric-item .el-icon {
  margin-right: 5px;
}

.create-time {
  text-align: right;
  font-size: 12px;
  color: #666;
  margin-bottom: 15px;
}

.actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.actions .el-button {
  width: 100%;
  margin-left: 0;
}

.comment-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.comment-list {
  flex: 1;
  overflow-y: auto;
  padding: 0 16px;
  margin-bottom: 16px;
}

.loading-container {
  padding: 20px;
}

.comments-wrapper {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.empty-comment {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #909399;
}

.empty-icon {
  font-size: 40px;
  margin-bottom: 10px;
}

.publish-comment {
  padding: 16px;
  border-top: 1px solid #ebeef5;
  background-color: #ffffff;
}
</style>
